package bb.lanxing.device.sgdevcie.xpair

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothDevice.ACTION_BOND_STATE_CHANGED
import android.bluetooth.BluetoothGatt
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Parcelable
import android.view.View
import android.view.animation.AlphaAnimation
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ProgressBar
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import bb.lanxing.R
import bb.lanxing.databinding.FragmentXpairPairingBinding
import bb.lanxing.device.sgdevcie.xpair.uimodel.BleDescriptionDevice
import bb.lanxing.device.sgdevcie.xpair.uimodel.RemoveFailedDevices
import bb.lanxing.device.sgdevcie.xpair.viewmodel.XPairViewModel
import bb.lanxing.lib.devices.sprint.utils.BleBondUtil
import bb.lanxing.lib.devices.sprint.utils.DeviceControllerHelper
import bb.lanxing.manager.SharedManager
import bb.lanxing.mvvm.base.BaseDBFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import android.util.Log;
import bb.lanxing.lib.devices.sprint.XossDevice
import bb.lanxing.lib.devices.sprint.XossDeviceController

class XPairPairingFragment :
    BaseDBFragment<FragmentXpairPairingBinding>(R.layout.fragment_xpair_pairing) {
    private val xPairViewModel by activityViewModels<XPairViewModel>()
    private var currentState: XPairState? = null
    private var gatt: BluetoothGatt? = null

    private val boundBroadcastReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                intent?.apply {
                    if (action == ACTION_BOND_STATE_CHANGED) {
                        val bluetoothDevice =
                            getParcelableExtra<Parcelable>("android.bluetooth.device.extra.DEVICE") as BluetoothDevice?
                        bluetoothDevice?.apply {
                            val pairTarget = xPairViewModel.pairTarget
                            val tempAddress = pairTarget?.address ?: ""
                            if (tempAddress == address) {
                                when (bondState) {
                                    10 -> {
                                        lifecycleScope.launch(Dispatchers.Main) {
                                            onBoundFailed()
                                        }
                                    }

                                    11 -> {
                                        lifecycleScope.launch(Dispatchers.Main) {
                                            onBounding()
                                        }
                                    }

                                    12 -> {
                                        lifecycleScope.launch(Dispatchers.Main) {
                                            onBoundSuccess()
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    fun onBoundFailed() {
        val progressBar: ProgressBar? = this.binding?.progress
        if (progressBar != null) {
            progressBar.visibility = View.GONE
        }
        switchState(XPairState.failed)
    }

    override fun initView(t: FragmentXpairPairingBinding?) {
        sendMessage(
            R.id.msg_change_title,
            getString(R.string.st_pair_your_device, xPairViewModel.xPairUIModel?.deviceName ?: "")
        )
        requireActivity().registerReceiver(
            boundBroadcastReceiver, IntentFilter(ACTION_BOND_STATE_CHANGED)
        )
        xPairViewModel.xPairUIModel ?: return
        binding.imgDevice.setImageResource(xPairViewModel.xPairUIModel!!.deviceIcon)
        val xPairPairUiModel = xPairViewModel.xPairUIModel!!.xPairPairUIModel ?: return
        binding.tvDes.text = xPairPairUiModel.pairTip
        doBound()
        binding.tvRetry.setOnClickListener {
            Log.d("wangsm_bt"," wangsm,do bound bt")
            //Log.d("BleBondUtil", "Remove bond result: $invoke")
            doBound()
        }
    }

    private fun doBound() {
        lifecycleScope.launch {
            switchState(XPairState.pairing)
            val pairTarget = xPairViewModel.pairTarget
            pairTarget?.let {
                val iterator = SharedManager.getInstance().removeFailedDevices.devices.iterator()
                var removeFailedDevices: RemoveFailedDevices? = null
                val address = it.device.address
                Log.d("wangsm_bt"," wangsm,device address: $address")
                while (iterator.hasNext()) {
                    val temp = iterator.next()
                    if (temp.address == address) {
                        removeFailedDevices = temp
                        break
                    }
                }
                if (BleBondUtil.isThisDeviceBounded(address) && null != removeFailedDevices) {
                    Log.d("wangsm_bt"," wangsm,onBoundSuccess")
                    onBoundSuccess()
                } else {
                    //test code
                   // XossDevice.ConnectTest()

                    BleBondUtil.createBondByConnect(it.device, {
                        Log.d("wangsm_bt"," wangsm,onBounding")
                        onBounding()
                    }, {
                        Log.d("wangsm_bt"," wangsm,onBoundFailed")
                        onBoundFailed()
                    }, { blue ->
                        gatt = blue
                        Log.d("wangsm_bt"," wangsm,onBoundSuccess")
                        onBoundSuccess()
                    })
                }
            }
        }
    }

    private fun switchState(xPairState: XPairState) {
        val frameLayout: FrameLayout?
        if (this.currentState == xPairState) {
            return
        }
        val i: Int = xPairState.ordinal
        if (i == 0) {
            val linearLayout2: LinearLayout? = if (binding != null) binding.llPairing else null
            if (linearLayout2 != null) {
                linearLayout2.visibility = View.VISIBLE
            }
            binding.llPairing.apply {
                clearAnimation()
                val alphaAnimation = AlphaAnimation(alpha, 1.0f).apply { duration = 500L }
                startAnimation(alphaAnimation)

            }
            frameLayout = if (binding != null) binding.llFailed else null
            if (frameLayout != null) {
                frameLayout.visibility = View.GONE
            }
            this.currentState = xPairState
        } else {
            val linearLayout4: LinearLayout? = if (binding != null) binding.llPairing else null
            if (linearLayout4 != null) {
                linearLayout4.visibility = View.GONE
            }
            frameLayout = if (binding != null) binding.llFailed else null
            if (frameLayout != null) {
                frameLayout.visibility = View.VISIBLE
            }
            binding.llFailed.apply {
                clearAnimation()
                val alphaAnimation = AlphaAnimation(alpha, 1.0f).apply { duration = 500L }
                startAnimation(alphaAnimation)

            }
            this.currentState = xPairState
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        requireActivity().unregisterReceiver(boundBroadcastReceiver)
    }

    fun onBounding() {
        val progressBar: ProgressBar? = if (binding != null) binding.progress else null
        if (progressBar == null) {
            return
        }
        progressBar.visibility = View.VISIBLE
    }

    fun onBoundSuccess() {
        val pairTarget: BleDescriptionDevice? = xPairViewModel.pairTarget
        pairTarget?.let {
            val iterator = SharedManager.getInstance().removeFailedDevices.devices.iterator()
            var removeFailedDevices: RemoveFailedDevices? = null
            val address = it.device.address
            while (iterator.hasNext()) {
                val temp = iterator.next()
                if (temp.address == address) {
                    removeFailedDevices = temp
                    break
                }
            }
            removeFailedDevices?.let { removed ->
                SharedManager.getInstance().removeRemoveFailedDevice(removed.address)
            }
            //wangsm_bt
            Log.d("wangsm_bt"," wangsm,device address: $pairTarget.address")
            Log.d("wangsm_bt"," wangsm,device name: $pairTarget.name")
            Log.d("wangsm_bt"," wangsm,device deviceType: $pairTarget.deviceType")
            val xossDevice = DeviceControllerHelper.getXossDeviceController(
                pairTarget.address, pairTarget.name, pairTarget.deviceType
            );

            if(xossDevice != null){
                xossDevice.connect()
            }else{
                Log.d("wangsm_bt"," wangsm,xossDevice is null,not connect")
            }

/*            DeviceControllerHelper.getXossDeviceController(
                pairTarget.address, pairTarget.name, pairTarget.deviceType
            ).connect()*/
        }
        val progressBar: ProgressBar? = if (binding != null) binding.progress else null
        if (progressBar != null) {
            progressBar.visibility = View.GONE
        }
        val activity = activity
        if (activity != null) {
            val intent = Intent()
            intent.putExtra(
                "EXTRA_DEVICE_NAME", pairTarget?.name
            )
            intent.putExtra(
                "EXTRA_DEVICE_ADDRESS", pairTarget?.address
            )
            intent.putExtra(
                "EXTRA_DEVICE_TYPE",
                if (pairTarget != null) Integer.valueOf(pairTarget.deviceType) else null
            )
            activity.setResult(-1, intent)
        }
        getActivity()?.finish()
    }
}